<template>
  <div class="data-table-container">
    <el-card class="table-card" shadow="hover">
      <!-- 表格头部操作区 -->
      <div class="table-header">
        <div class="header-left">
          <slot name="header-left">
            <h3 class="table-title">{{ title }}</h3>
          </slot>
        </div>
        <div class="header-right">
          <slot name="header-right">
          </slot>
        </div>
      </div>

      <!-- 筛选器 -->
      <div v-if="showFilters && filters.length > 0" class="table-filters">
        <div class="filter-row">
          <div class="filter-items">
            <el-form :model="filterForm" inline>
              <el-form-item
                v-for="filter in filters"
                :key="filter.prop"
                :label="filter.label"
              >
                <!-- 选择器筛选 -->
                <el-select
                  v-if="filter.type === 'select'"
                  v-model="filterForm[filter.prop]"
                  :placeholder="`请选择${filter.label}`"
                  :style="{ width: filter.width || '140px' }"
                  clearable
                  @change="handleFilterChange"
                >
                  <el-option
                    v-for="option in filter.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
                
                <!-- 日期范围筛选 -->
                <el-date-picker
                  v-else-if="filter.type === 'daterange'"
                  v-model="filterForm[filter.prop]"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="handleFilterChange"
                />
                
                <!-- 输入框筛选 -->
                <el-input
                  v-else
                  v-model="filterForm[filter.prop]"
                  :placeholder="`请输入${filter.label}`"
                  clearable
                  @input="handleFilterChange"
                />
              </el-form-item>
            </el-form>
          </div>
          
          <div class="filter-actions">
            <!-- 刷新按钮 -->
            <el-button
              v-if="showRefresh"
              :loading="loading"
              @click="handleRefresh"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            
            <!-- 重置按钮 -->
            <el-button
              @click="resetFilters"
            >
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
            
            <!-- 搜索框 -->
            <el-input
              v-if="showSearch"
              v-model="localSearchKeyword"
              placeholder="搜索..."
              style="width: 150px; margin-left: 10px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 批量操作区 -->
      <div v-if="showBatchActions && selectedRows.length > 0" class="batch-actions">
        <div class="batch-info">
          <span>已选择 {{ selectedRows.length }} 项</span>
          <el-button type="text" @click="clearSelection">取消选择</el-button>
        </div>
        <div class="batch-buttons">
          <slot name="batch-actions" :selectedRows="selectedRows">
            <el-button type="danger" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </slot>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        :border="border"
        :stripe="stripe"
        :size="size"
        :height="height"
        :max-height="maxHeight"
        :default-sort="defaultSort"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @row-click="handleRowClick"
        @row-dblclick="handleRowDoubleClick"
      >
        <!-- 选择列 -->
        <el-table-column
          v-if="showSelection"
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        
        <!-- 序号列 -->
        <el-table-column
          v-if="showIndex"
          type="index"
          label="序号"
          width="60"
          align="center"
          fixed="left"
          :index="getIndex"
        />

        <!-- 数据列 -->
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :align="column.align || 'left'"
          :sortable="column.sortable"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <template #default="scope">
            <slot :name="column.prop" :row="scope.row" :column="column" :index="scope.index">
              <!-- 自定义渲染 -->
              <div v-if="column.render" v-html="column.render(scope.row[column.prop], scope.row)"></div>
              
              <!-- 标签显示 -->
              <el-tag
                v-else-if="column.type === 'tag'"
                :type="getTagType(scope.row[column.prop], column.tagMap)"
              >
                {{ getTagLabel(scope.row[column.prop], column.tagMap) }}
              </el-tag>
              
              <!-- 开关显示 -->
              <el-switch
                v-else-if="column.type === 'switch'"
                v-model="scope.row[column.prop]"
                :disabled="column.disabled"
                @change="(val) => handleSwitchChange(val, scope.row, column)"
              />
              
              <!-- 图片显示 -->
              <el-image
                v-else-if="column.type === 'image'"
                :src="scope.row[column.prop]"
                :preview-src-list="[scope.row[column.prop]]"
                style="width: 50px; height: 50px"
                fit="cover"
              />
              
              <!-- 链接显示 -->
              <el-link
                v-else-if="column.type === 'link'"
                type="primary"
                @click="handleLinkClick(scope.row, column)"
              >
                {{ scope.row[column.prop] }}
              </el-link>
              
              <!-- 普通文本 -->
              <span v-else>{{ formatValue(scope.row[column.prop], column) }}</span>
            </slot>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          v-if="showActions && actions.length > 0"
          label="操作"
          :width="actionsWidth"
          fixed="right"
          align="center"
        >
          <template #default="scope">
            <slot name="actions" :row="scope.row" :index="scope.index">
              <div class="action-buttons">
                <el-button
                  v-for="action in getVisibleActions(scope.row)"
                  :key="action.key"
                  :type="action.type || 'text'"
                  :size="action.size || 'small'"
                  :disabled="action.disabled && action.disabled(scope.row)"
                  :title="action.title || action.label"
                  @click="handleAction(action, scope.row, scope.$index)"
                >
                  <el-icon v-if="action.icon">
                    <component :is="action.icon" />
                  </el-icon>
                </el-button>
              </div>
            </slot>
          </template>
        </el-table-column>

        <!-- 空数据提示 -->
        <template #empty>
          <div class="empty-data">
            <el-icon size="64" color="#C0C4CC">
              <DocumentDelete />
            </el-icon>
            <p>{{ emptyText }}</p>
          </div>
        </template>
      </el-table>

      <!-- 分页器 -->
      <div v-if="showPagination" class="table-pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="pageSizes"
          :total="total"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="handleCurrentChange"
          @update:page-size="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { 
  Search, 
  Refresh, 
  RefreshLeft,
  Delete, 
  DocumentDelete 
} from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { debounce, formatDateTime } from '@/utils'

const props = defineProps({
  // 表格标题
  title: {
    type: String,
    default: ''
  },
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true
  },
  // 操作按钮配置
  actions: {
    type: Array,
    default: () => []
  },
  // 筛选器配置
  filters: {
    type: Array,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 分页配置
  pagination: {
    type: Object,
    default: () => ({
      current: 1,
      size: 10,
      total: 0
    })
  },
  // 表格属性
  border: {
    type: Boolean,
    default: true
  },
  stripe: {
    type: Boolean,
    default: true
  },
  size: {
    type: String,
    default: 'default'
  },
  height: {
    type: [String, Number],
    default: undefined
  },
  maxHeight: {
    type: [String, Number],
    default: undefined
  },
  defaultSort: {
    type: Object,
    default: () => ({})
  },
  // 功能开关
  showSearch: {
    type: Boolean,
    default: true
  },
  showRefresh: {
    type: Boolean,
    default: true
  },
  showFilters: {
    type: Boolean,
    default: true
  },
  showSelection: {
    type: Boolean,
    default: false
  },
  showIndex: {
    type: Boolean,
    default: true
  },
  showActions: {
    type: Boolean,
    default: true
  },
  showBatchActions: {
    type: Boolean,
    default: false
  },
  showPagination: {
    type: Boolean,
    default: true
  },
  // 搜索关键字
  searchKeyword: {
    type: String,
    default: ''
  },
  // 其他配置
  actionsWidth: {
    type: [String, Number],
    default: 180
  },
  emptyText: {
    type: String,
    default: '暂无数据'
  },
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  }
})

const emit = defineEmits([
  'update:searchKeyword',
  'refresh',
  'search',
  'filter-change',
  'selection-change',
  'sort-change',
  'row-click',
  'row-dblclick',
  'action',
  'batch-delete',
  'page-change',
  'size-change',
  'switch-change',
  'link-click'
])

// 组件引用
const tableRef = ref()

// 数据状态
const tableData = ref([...props.data])
const selectedRows = ref([])
const localSearchKeyword = ref(props.searchKeyword)
const filterForm = ref({})

// 监听搜索关键字变化
watch(() => props.searchKeyword, (newKeyword) => {
  localSearchKeyword.value = newKeyword
})

// 分页状态
let currentPage = props.pagination.current
let pageSize = props.pagination.size
const total = ref(props.pagination.total)

// 监听外部数据变化
watch(() => props.data, (newData) => {
  tableData.value = [...newData]
})

watch(() => props.pagination, (newPagination) => {
  currentPage = newPagination.current
  pageSize = newPagination.size
  total.value = newPagination.total
}, { deep: true })

// 计算序号
const getIndex = (index) => {
  return (currentPage - 1) * pageSize + index + 1
}

// 搜索处理（防抖）
const handleSearch = debounce(() => {
  emit('update:searchKeyword', localSearchKeyword.value)
  emit('search', localSearchKeyword.value)
}, 300)

// 筛选变化处理
const handleFilterChange = () => {
  emit('filter-change', filterForm.value)
}

// 重置筛选
const resetFilters = () => {
  filterForm.value = {}
  emit('filter-change', {})
}

// 刷新处理
const handleRefresh = () => {
  emit('refresh')
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 清空选择
const clearSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 排序变化处理
const handleSortChange = (sortInfo) => {
  emit('sort-change', sortInfo)
}

// 行点击处理
const handleRowClick = (row, column, event) => {
  emit('row-click', row, column, event)
}

// 行双击处理
const handleRowDoubleClick = (row, column, event) => {
  emit('row-dblclick', row, column, event)
}

// 操作按钮处理
const handleAction = (action, row, index) => {
  emit('action', action.key, row, index)
}

// 批量删除处理
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 项数据吗？`,
      '批量删除',
      {
        type: 'warning'
      }
    )
    emit('batch-delete', selectedRows.value)
  } catch {
    // 用户取消
  }
}

// 分页变化处理
const handleCurrentChange = (page) => {
  currentPage = page
  emit('page-change', page)
}

const handleSizeChange = (size) => {
  pageSize = size
  currentPage = 1
  emit('size-change', size)
}

// 开关变化处理
const handleSwitchChange = (value, row, column) => {
  emit('switch-change', value, row, column)
}

// 链接点击处理
const handleLinkClick = (row, column) => {
  emit('link-click', row, column)
}

// 获取可见的操作按钮
const getVisibleActions = (row) => {
  return props.actions.filter(action => {
    return !action.show || action.show(row)
  })
}

// 获取标签类型
const getTagType = (value, tagMap) => {
  return tagMap && tagMap[value] ? tagMap[value].type : 'info'
}

// 获取标签文本
const getTagLabel = (value, tagMap) => {
  return tagMap && tagMap[value] ? tagMap[value].label : value
}

// 格式化值
const formatValue = (value, column) => {
  if (value === null || value === undefined) return ''
  
  if (column.formatter) {
    return column.formatter(value)
  }
  
  if (column.type === 'datetime') {
    return formatDateTime(value)
  }
  
  if (column.type === 'date') {
    return formatDateTime(value, 'YYYY-MM-DD')
  }
  
  return value
}

// 暴露方法
defineExpose({
  clearSelection,
  toggleRowSelection: (row, selected) => {
    if (tableRef.value) {
      tableRef.value.toggleRowSelection(row, selected)
    }
  },
  toggleAllSelection: () => {
    if (tableRef.value) {
      tableRef.value.toggleAllSelection()
    }
  },
  setCurrentRow: (row) => {
    if (tableRef.value) {
      tableRef.value.setCurrentRow(row)
    }
  }
})
</script>

<style scoped>
.data-table-container {
  width: 100%;
  user-select: none;
  -webkit-user-drag: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
}

.data-table-container * {
  user-select: text;
  -webkit-user-drag: none;
  -webkit-touch-callout: none;
}

.table-card {
  border-radius: 8px;
  border: none;
}

/* 表格容器 */
.el-table {
  width: 100%;
}

/* 表格头部按钮组 */
.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.header-actions .el-button,
.header-actions .el-input {
  margin-bottom: 0;
}

/* 表格头部 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.table-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 筛选器 */
.table-filters {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 筛选器行 */
.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: nowrap;
}

.filter-items {
  display: flex;
  flex-wrap: nowrap;
  gap: 16px;
  align-items: center;
}

.filter-items .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.filter-items .el-form-item__label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

/* 筛选器选择框 */
.filter-items .el-select {
  width: 140px;
}

/* 筛选器操作按钮组 */
.filter-actions {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 10px;
}

.filter-actions .el-button,
.filter-actions .el-input {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .filter-items {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .filter-actions {
    justify-content: center;
  }
}

/* 批量操作 */
.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #e3f2fd;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.batch-info {
  color: #606266;
  font-size: 14px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
  padding: 8px 12px;
}

/* 显示文字和图标 */
.action-buttons .el-button span {
  display: inline;
}

.action-buttons .el-button .el-icon {
  margin-right: 5px;
}

/* 确保按钮有合适的内边距 */
.action-buttons .el-button {
  padding: 8px 10px;
}

/* 空数据 */
.empty-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.empty-data p {
  margin: 16px 0 0 0;
  font-size: 14px;
}

/* 分页器 */
.table-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* PC端优化设计 */
@media (max-width: 1200px) {
  .table-header {
    flex-wrap: wrap;
  }
  
  .header-right {
    flex-wrap: wrap;
  }
}

@media (max-width: 992px) {
  .batch-actions {
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-right {
    justify-content: flex-end;
  }
  
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .table-pagination {
    justify-content: center;
  }
}
</style>